import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/Login'
import Layout from '@/views/Layout'
import { getToken } from '@/utils/storage.js'
import Home from '@/views/Layout/Home'
import Articles from '@/views/Layout/Articles'
import Pictures from '@/views/Layout/Pictures'
import NotFound from '@/views/NotFound'
import AddArticle from '@/views/Layout/Articles/add.vue'

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/login', component: Login },
    {
      path: '/',
      component: Layout,
      children: [
        {
          path: '/',
          component: Home
        },
        {
          path: '/articles',
          component: Articles
        },
        {
          path: '/pictures',
          component: Pictures
        },
        {
          path: '/add',
          component: AddArticle
        }
      ]
    },
    { path: '*', component: NotFound }

  ]
})

// 配置路由的导航守卫
// beforeEach提供的函数会在所有的路由发生跳转之前。
// next()   如果直接调用next()代表放行   next('/login') 代表跳转到login
// 1. 如果有token, 或者去登录 就直接放行
// 2. 否则就拦截到登录去
router.beforeEach((to, from, next) => {
  const token = getToken()
  if (token || to.path === '/login') {
    next()
  } else {
    next('/login')
  }
})

export default router
